import axios from 'axios';
import {ElMessage} from 'element-plus';
import router from '@/router';

const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // const userStore = useUserStoreHook();
    // if (userStore.token && /^[0-9a-zA-Z]*$/.test(userStore.token)) {
    //   config.headers.Authorization = userStore.token;
    //   config.headers.os = 'pc';
    // }
    return config;
  },
  error => Promise.reject(error),
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    const {code, msg} = response.data;
    const logoutCodes = [207, 200, 403, 8001, 703];

    if (logoutCodes.includes(code)) {
      if (!service.msg) {
        service.msg = ElMessage({
          type: 'error',
          message: msg || 'Error',
          onClose: () => service.msg = null,
        });
      }

      const {pathname, search} = window.location;
      router.replace({ path: `/login?redirect=${pathname + search}` });
    } else {
      return response;
    }
  },
  error => {
    if (error.response.data) {
      const {code, msg} = error.response.data;
      ElMessage.error(msg || '系统出错');
    }
    return Promise.reject(error.message);
  },
);

export default service;